package ee.maoinvest.backend.model.dao.postgresqlimplementations;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import ee.maoinvest.backend.database.ConnectionManager;
import ee.maoinvest.backend.model.dao.ElectricityMeterTypeDAO;
import ee.maoinvest.backend.model.data.ElectricityMeterType;

public class ElectricityMeterTypeDAOPostgresqlImpl implements ElectricityMeterTypeDAO
{
	Logger logger = Logger.getLogger(ElectricityMeterTypeDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	private final int WARNING_NO_ROWS_AFFECTED = 0;
	private int rowsAffected;
	
	public ElectricityMeterTypeDAOPostgresqlImpl(Connection dbConnection)
	{
		this.dbConnection = dbConnection;
	}
	
//-----------------START OF BASIC CRUD-----------------------------------

	@Override
	public int insertElectricityMeterType(
			ElectricityMeterType electricityMeterType) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "INSERT INTO Electricity_meter_types (electricityMeterTypeID, typeName) " + 
				"VALUES (?, ?);";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			
			preparedStatement.setInt	(	1, electricityMeterType.getElectricityMeterTypeID());
			preparedStatement.setString	(	2, electricityMeterType.getTypeName());
			
			logger.info(preparedStatement.toString());
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				resultSet = preparedStatement.getGeneratedKeys();
				resultSet.next(); //answer consist only 1 row, so move the cursor just once to start to process the result
				int newId = resultSet.getInt(1); // 1, because identifiers are held in the first column 
				electricityMeterType.setElectricityMeterTypeID(newId);
				return rowsAffected;
			}
			else
			{
				System.out.println("No rows affected!");
				logger.info("Unsuccessful insertion to a database: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public ElectricityMeterType getElectricityMeterTypeByID(
			int electricityMeterTypeID) 
	{
		resultSet = null;
		ElectricityMeterType electricityMeterTypeRetrieved = null;
		sql = "SELECT * FROM Electricity_meter_types WHERE electricityMeterTypeID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, electricityMeterTypeID);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				electricityMeterTypeRetrieved = new ElectricityMeterType();
				electricityMeterTypeRetrieved.setElectricityMeterTypeID(resultSet.getInt("electricityMeterTypeID"));
				electricityMeterTypeRetrieved.setTypeName(resultSet.getString("typeName"));
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return electricityMeterTypeRetrieved;
	}

	@Override
	public int updateElectricityMeterType(
			int oldElectricityMeterTypeID, ElectricityMeterType electricityMeterType) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "UPDATE Electricity_meter_types " + 
				"SET electricityMeterTypeID = ?, typeName = ? " + 
				"WHERE electricityMeterTypeID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			
			preparedStatement.setInt	(	1, electricityMeterType.getElectricityMeterTypeID());
			preparedStatement.setString	(	2, electricityMeterType.getTypeName());
			preparedStatement.setInt	(	3, oldElectricityMeterTypeID);
			
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Update sucessful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.error("Update was unsuccesful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
			return WARNING_NO_ROWS_AFFECTED;		
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public int deleteElectricityMeterType(int electricityMeterTypeID) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "DELETE FROM Electricity_meter_types WHERE electricityMeterTypeID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			preparedStatement.setInt(1, electricityMeterTypeID);
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Deletion successful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.info("Deletion unsuccessful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch(SQLException e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}
//-----------------END OF BASIC CRUD-----------------------------------

	@Override
	public List<ElectricityMeterType> getAllElectricityMeterTypes() 
	{
		List<ElectricityMeterType> listOfElectricityMeterTypes = new ArrayList<ElectricityMeterType>();
		ElectricityMeterType electricityMeterTypeRetrieved = null;
		sql = "SELECT * FROM Electricity_meter_types;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
					sql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY
				);
			
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of the result set. Otherwise it can not start reading the result set. 
			resultSet.beforeFirst();
			
			while (resultSet.next())
			{	
				electricityMeterTypeRetrieved = new ElectricityMeterType();
				electricityMeterTypeRetrieved.setElectricityMeterTypeID(resultSet.getInt("electricityMeterTypeID"));
				electricityMeterTypeRetrieved.setTypeName(resultSet.getString("typeName"));
				
				listOfElectricityMeterTypes.add(electricityMeterTypeRetrieved);
			}
		} 
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return listOfElectricityMeterTypes;
	
	}
	
	
}
